<?php
echo "<a href='?page=main'>[Lobby]</a>&nbsp;";

$tbl = false;

if(isset($p["id"])) {
	$_SESSION["table"] = $p["id"];
}

if(isset($_SESSION["table"])) {
	$tbl = DB::load($_SESSION["table"]);
} else {
	Utils::redirect('?page=main');
}

if($tbl==false) {
	Utils::redirect('?page=main');
}


if(isset($p["unregister"])) {
	$tbl->unregister($usrId);
	DB::save($tbl);
}

if(isset($p["register"])) {
	$tbl->register($usrId);
	DB::save($tbl);
}

///// TTT

$ttt = $tbl;

if(isset($p["restart"])){
	$ttt->restart();
	DB::save($ttt);
}

if(isset($p["mv"])){
	$ttt->doMove($usrId, $p["mv"]);
	DB::save($ttt);
}

$cur = $ttt->amICurrent($usrId);
$win = $ttt->winner;

function cell($ix) {
	global $ttt, $cur, $win;
	if($ttt->field[$ix]==1) {
		echo "O";
	} else if($ttt->field[$ix]==2) {
		echo "X";
	} else {
		if($cur && $win==0) {
			echo "<a href='?page=table&mv=".$ix."'>#</a>";
		} else {
			echo "&nbsp;&nbsp;";
		}
	}
}

echo "<hr>";
if($ttt->player1) {
	echo DB::load($ttt->player1)->name;
	echo " (O) / ";
	if($ttt->player2) {
		echo DB::load($ttt->player2)->name." (X) ";
	} else {
		echo "<a href='?page=table&register'>Register</a>";
	}
} else {
	echo "<a href='?page=table&register'>Register</a>";
}

?>

<table border="1">
<tr>
<td><?php cell(0); ?></td>
<td><?php cell(1); ?></td>
<td><?php cell(2); ?></td>
</tr>
<tr>
<td><?php cell(3); ?></td>
<td><?php cell(4); ?></td>
<td><?php cell(5); ?></td>
</tr>
<tr>
<td><?php cell(6); ?></td>
<td><?php cell(7); ?></td>
<td><?php cell(8); ?></td>
</tr>
</table>

<?php

if($win!=0) {
	$www = $ttt->getWinnerUser();
	echo "<h3>The winner is ".$www->name."</h3><br>";
	echo "<a href='?page=table&restart'>[Restart]</a>";
}

echo "&nbsp;<a href='?page=table&unregister'>[Sitout]</a>";

?>

<SCRIPT LANGUAGE="JavaScript">
<!--
var sURL = unescape(window.location.pathname);
setTimeout( "refresh()", 2*1000 );
function refresh()
{
    window.location.href = sURL;
}
//-->
</SCRIPT>